from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.db.models import Q

from web import md5
from web import models
import re


class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机格式错误')])
    password = forms.CharField(label='密码', widget=forms.PasswordInput, min_length=8, error_messages={'min_length':'密码太短'})
    confirm_password = forms.CharField(label='重复密码', widget=forms.PasswordInput)
    class Meta:
        model = models.UserInfo
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name,field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入{}'.format(field.label)

    """钩子函数"""
    def clean_username(self):
        username = self.cleaned_data['username']
        exists = models.UserInfo.objects.filter(username=username).exists()
        if exists:
            raise ValidationError('用户名已存在')
        return username

    def clean_password(self):
        pwd = self.cleaned_data['password']
        # 加密 & 返回
        return md5.md5_str(pwd)

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get('password')
        confirm_pwd = md5.md5_str(self.cleaned_data['confirm_password'])
        if pwd != confirm_pwd:
            raise ValidationError('密码不一致')
        return confirm_pwd


class Login_Form(forms.Form):
    username = forms.CharField(label='用户名或手机号')
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    img_code = forms.CharField(label='验证码')

    def __init__(self,request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        for name,field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入{}'.format(field.label)

    def clean_username(self):
        username = self.cleaned_data['username']
        # exists = models.UserInfo.objects.filter(username=username).exists()
        # 用户名或者手机号登陆
        exists = models.UserInfo.objects.filter(Q(username=username)|Q(mobile_phone=username)).exists()
        if not exists:
            raise ValidationError('用户名错误')
        return username

    def clean_password(self):
        pwd = md5.md5_str(self.cleaned_data['password'])
        exists = models.UserInfo.objects.filter(password=pwd).exists()
        if not exists:
            raise ValidationError('密码错误')
        return pwd

    def clean_img_code(self):
        img_code = self.cleaned_data['img_code']
        session_code = self.request.session.get('img_code')
        if not session_code:
            raise ValidationError('验证码已过期 请从新输入')
        if img_code != session_code:
            raise ValidationError('验证码错误')
        self.request.session.set_expiry(3600*24*7)
        return img_code